angular.module('moti.directive.uploaderAudio', ['moti.directive.modal'])
    .directive('uploaderAudio', ['$modal', function($modal){
        return {
            restrict : 'E',
            replace : true,
            templateUrl : 'views/uploaderAudio.html',
            scope : {
                val : '='
            },
            link : function(scope, elem){
                var $wrap = elem,
                    $name = $wrap.find('.recordName'),
                    $upload = $wrap.find('.recordBtn'),
                    uploader;
                $upload.hide();

                uploader = WebUploader.create({
                    pick: {
                        id: $wrap.find('.recordPicker'),
                        label: '点击选择录音',
                        multiple: false
                    },
                    accept: {
                        title: 'Audio',
                        extensions: 'mp3',
                        mimeTypes: 'audio/mp3'
                    },
                    server: 'http://up.qiniu.com/'
                });

                var loading_modal;
                uploader.on('uploadBeforeSend', function(obj, data, headers) {
                    data.token = QINIU.UP_TOKEN;
                    data.key = 'spots/' + Math.uuid();
                    loading_modal = $modal({
                        id : 'loading-modal',
                        text : '上传中...'
                    });
                    loading_modal.show();
                });

                uploader.onFileQueued = function(file) {
                    $name.text(file.name);
                    $upload.show();
                };

                uploader.on('uploadSuccess', function(file, response) {
                    $.ajax({
                        type: "post",
                        url: INTERFACE_API.UPLOADAUDIO,
                        headers: {
                            "Authorization" : "Bearer " + localStorage.getItem("U_INFO")
                        },
                        data: {
                            url: response.url
                        },
                        success: function(audio) {
                            scope.val = audio.audio_id;
                            loading_modal.hide();
                            $modal({id : 'tip-modal', text : "上传成功"}).show().autoHide();
                        }
                    });
                });

                $upload.on( 'click', function() {
                    uploader.upload();
                });
            }
        };
    }]);